package com.senmiao.ssm.realm;

import com.senmiao.ssm.entity.Admin;
import com.senmiao.ssm.pojo.AdminShiro;
import com.senmiao.ssm.service.RealmService;
import com.senmiao.ssm.pojo.MySimpleByteSource;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class MyRealm extends AuthorizingRealm {

    @Autowired
    private RealmService realmService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("========授权========");

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        // 获取登陆者的信息
        AdminShiro principal = (AdminShiro) principalCollection.getPrimaryPrincipal();
        // 查权限
        Integer adminId = principal.getId();
        Set<String> permissions =  realmService.getPermissionsOfAdminByAdminId(adminId);
        simpleAuthorizationInfo.setStringPermissions(permissions);
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("========认证========");

        // 获取用户输入的账号
        String account = authenticationToken.getPrincipal().toString();

        // 查询数据库
        Admin admin = realmService.getAdminByAccount(account);
        if (admin != null){
            AdminShiro adminShiro = new AdminShiro();
            adminShiro.setId(admin.getId());
            adminShiro.setAccount(admin.getAccount());
            // 返回认证信息
            return new SimpleAuthenticationInfo(adminShiro, admin.getPassword(), new MySimpleByteSource(admin.getSalt().getBytes()), getName());
        }
        return null;
    }
}